#include "fcntl.h"
#include "stat.h"
#include "fs.h"
#include "fat32.h"
#include "fat32.c"
#include "mmap.h"

struct dirent*
create(char *path, short type)
{
  struct dirent *ep, *dp;
  char name[FAT32_MAX_FILENAME + 1];
  if((dp = enameparent(path, name)) == 0)
    return 0;
  elock(dp);
  if((ep = ealloc(dp, name, type == T_DIR)) == 0){
    eunlock(dp);
    eput(dp);
    return 0;
  }
  elock(ep);
  // what needs to do ?
  eunlock(dp);
  eput(dp);

  return ep;
}


//返回文件描述符fd
int fs_file_open(char* path,int omode)
{
  int fd;
  struct fs_file *f;
  struct dirent *ep;
  if(omode & O_CREATE){
    ep = create(path, T_FILE);
    if(ep == 0){
      return -1;
    }
  } else {
    if((ep = ename(path)) == 0){
      return -1;
    }
    elock(ep);
    if((ep->attribute & ATTR_DIRECTORY) && omode != O_RDONLY){
      eunlock(ep);
      eput(ep);
      return -1;
    }
  }

  if((f = filealloc()) == 0){
    eunlock(ep);
    eput(ep);
    return -1;
  }
  if((ep->attribute & ATTR_DEVICE) != 0) {
      f->major = 0; f->minor = devsw[0].open();
      f->type = FD_DEVICE;
  }
  else f->type = FD_ENTRY;
  f->off = 0;
  f->ep = ep;
  f->readable = !(omode & O_WRONLY);
  f->writable = (omode & O_WRONLY) || (omode & O_RDWR);
  
  if ((fd = fdalloc(f)) < 0){
    eunlock(ep);
    fs_fileclose(f);
    return -1;
  }

  eunlock(ep);

  return fd;
}
